﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using SYcwpb.Controls;
using SYcwpb.Models;
using SYcwpb.Commands;
using System.Windows.Input;
using SYcwpb.Helpers;
using SYcwpb.Views;
using SYcwpb.WinForm;
using SYcwpb.WinForm.JCT;
using System.Threading;
using SYcwpb.Access;
using System.Media;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Reflection;
using System.Text.RegularExpressions;

namespace SYcwpb.ViewModels
{
    class MainViewModel : ViewModelBase
    {
        private LoginModel _userModel;
        private string _timeTable = "无";
        private string _softDay = "0";
        private string _SoftMile = "0";

        private MainView _mainView;

        private ICommand _executeCommand;
        private ICommand _attendCommand;
        private ICommand _offWorkCommand;
        private ICommand _selDriverCommand;

        private string _bbShowTime = "07:00:00";  //开始显示白班司机的时间
        private string _ybShowTime = "14:30:00";  //开始显示夜班司机的时间

        private string _driverID;
        private string _pasWrd;

     
   

        //private bool _isReplace;
        private bool IsVoiceOpen = true;

        /// <summary>
        /// 判断今天是否执行过安排交路到司机
        /// </summary>
        private bool _isCrossRoadAdd = false;
        private Thread UpdateDutyInfoThread = null;
        private Thread RemindingDriverTherad = null;
        private SoundPlayer _soundPlayer = null;
        private SoundPlayer _remindSoundPlayer = null;
        private DriverTeamAccess _teamAccess;
        private AttendAccess _attendAccess;
        private TimeTableAccess _timeTableAccess;

        private ObservableCollection<CtlDutyInfo> _mainDriverCollections = new ObservableCollection<CtlDutyInfo>()
        {
            new CtlDutyInfo(),
            new CtlDutyInfo(),
            new CtlDutyInfo(),
            new CtlDutyInfo(),
            new CtlDutyInfo(),
            new CtlDutyInfo(),
            new CtlDutyInfo(),
            new CtlDutyInfo(),
            new CtlDutyInfo(),
            new CtlDutyInfo(),
        };
        public ObservableCollection<CtlDutyInfo> MainDriverCollections
        {
            get { return _mainDriverCollections; }
            set
            {
                _mainDriverCollections = value;

                OnPropertyChanged("MainDriverCollections");
            }
        }

        private ObservableCollection<DutyInfoModel> _crossingRoadCollections = new ObservableCollection<DutyInfoModel>();
        public ObservableCollection<DutyInfoModel> CrossingRoadCollections
        {
            get { return _crossingRoadCollections; }
            set
            {
                _crossingRoadCollections = value;

                OnPropertyChanged("CrossingRoadCollections");
            }
        }
        private ObservableCollection<AttenInfoMedel> _attendInfoList = new ObservableCollection<AttenInfoMedel>();
        public ObservableCollection<AttenInfoMedel> AttendInfoList
        {
            get { return _attendInfoList; }
            set
            {
                _attendInfoList = value;
            }
        }

        public LoginModel UserModel
        {
            get
            {
                if (null == _userModel)
                    _userModel = CONSTDATA.UserModel;

                return _userModel;
            }
            set
            {
                _userModel = value;

                OnPropertyChanged("UserModel");
            }
        }

        public string TimeTable
        {
            get { return _timeTable; }
            set
            {
                _timeTable = value;
                OnPropertyChanged("TimeTable");
            }
        }

        public string SoftDay
        {
            get { return _softDay; }
            set
            {
                _softDay = value;
                OnPropertyChanged("SoftDay");
            }
        }

        public string SoftMile
        {
            get { return _SoftMile; }
            set
            {
                _SoftMile = value;
                OnPropertyChanged("SoftMile");
            }
        }

        public string DriverID
        {
            get { return _driverID; }
            set
            {
                _driverID = value;
                OnPropertyChanged("DriverID");
            }
        }

        //public bool IsReplace
        //{
        //    get { return _isReplace; }
        //    set
        //    {
        //        _isReplace = value;
        //        OnPropertyChanged("IsReplace");
        //    }
        //}

        public string PasWrd
        {
            get { return _pasWrd; }
            set
            {
                _pasWrd = value;
                OnPropertyChanged("PasWrd");
            }
        }

        public ICommand ExecuteCommand
        {
            get
            {
                _executeCommand = new RelayCommands(Para => onExecute(Para));
                return _executeCommand;
            }

        }

        public ICommand AttendCommand
        {
            get
            {
                if (null == _attendCommand)
                    _attendCommand = new RelayCommands(para => this.AttendMethod());

                return _attendCommand;
            }
        }

        public ICommand OffWorkCommand
        {
            get
            {
                if (null == _offWorkCommand)
                    _offWorkCommand = new RelayCommands(para => this.OffWorkMethod());

                return _offWorkCommand;
            }
        }

        public ICommand SelDriverCommand
        {
            get
            {
                if (null == _selDriverCommand)
                    _selDriverCommand = new RelayCommands(para => this.SelDriverByListView());

                return _selDriverCommand;
            }
        }

        public MainViewModel(MainView view)
        {



            this._mainView = view;

            _teamAccess = new DriverTeamAccess(Convert.ToInt32(UserModel.Line));

            _attendAccess = new AttendAccess();

            _timeTableAccess = new TimeTableAccess();

            LoadSound();

            LoadRemindSound();

            InitThread();

            RemindDriverTherad();
        }

        public void Load()
        {
            LoadTimeTable();
            //加载行车安全行车天数
            LoadSoftDay();
            //加载行车安全公里数
            LoadSoftMile();
        }

        public void Close()
        {
            if (!MessageBoxHelper.ConfirmYesNo("确定退出系统吗？"))
            {
                return;
            }

            _mainView.Dispatcher.Invoke(new Action(_mainView.Close));
        }

        private void LoadTimeTable()
        {
            string timeTable = _timeTableAccess.GetTodayTimeTable();

            if (!string.IsNullOrEmpty(timeTable) && TimeTable.CompareTo(timeTable) != 0)
            {
                TimeTable = timeTable;
            }
        }

        private void LoadSoftDay()
        {
            string softDay = _timeTableAccess.GetSoftDay();
            if (!string.IsNullOrEmpty(softDay))
            {
                TimeSpan midTime = DateTime.Now - Convert.ToDateTime(softDay);
                SoftDay = midTime.Days.ToString();
            }

        }
        /// <summary>
        /// 安全公里数
        /// </summary>
        private void LoadSoftMile()
        {
            //判断安全时间是否大于系统设定时间 如果小于 那么加上初始化值
            string softDay = _timeTableAccess.GetSoftDay();
            string iniMile = _timeTableAccess.GetIniMiles();


            string softMile = _timeTableAccess.GetSoftMile();
            if (!string.IsNullOrEmpty(softMile))
            {
                // TimeSpan midTime = DateTime.Now - Convert.ToDateTime(softDay);
                if (Convert.ToDateTime(softDay) < Convert.ToDateTime("2103-12-03"))
                {
                    SoftMile = Convert.ToString(Convert.ToDecimal(softMile) + Convert.ToDecimal(iniMile));
                }
                else
                {
                    SoftMile = softMile;
                }
            }

        }



        /// <summary>
        /// 加载提示音
        /// </summary>
        private void LoadSound()
        {
            string soundPath = Application.StartupPath + @"\Sound\msg.wav";
            if (!File.Exists(soundPath))
            {
                MessageBoxHelper.ShowError("加载出勤提示音失败！请检查提示音文件是否存在！");
                return;
            }
            _soundPlayer = new SoundPlayer(soundPath);
        }


        private void LoadRemindSound()
        {
            string soundPath = Application.StartupPath + @"\Sound\RemindMsg.wav";

            if (!File.Exists(soundPath))
            {
                MessageBoxHelper.ShowError("加载出勤提示音失败！请检查提示音文件是否存在！");
                return;
            }
            _remindSoundPlayer = new SoundPlayer(soundPath);

            //Stream stm = Assembly.GetExecutingAssembly().GetManifestResourceStream("SYcwpb.Sound.RemindMsg.wav");
            //if (stm != null)
            //    _remindSoundPlayer = new SoundPlayer(stm);
        }


        private void InitThread()
        {
            UpdateDutyInfoThread = new Thread(new ThreadStart(UpdateFunction));
            UpdateDutyInfoThread.SetApartmentState(ApartmentState.STA);
            UpdateDutyInfoThread.IsBackground = true;
            UpdateDutyInfoThread.Start();
        }

        private void UpdateFunction()
        {
            while (true)
            {
                try
                {
                    if (CheckHasRefreshCrossRoad())
                    {
                        DataTable dutyInfoDT = _teamAccess.GetDriverInfoByClass();

                        if (dutyInfoDT != null && dutyInfoDT.Rows.Count > 0)
                        {
                            _mainView.Dispatcher.Invoke(new UpdateDelegate(UpdateDriverInfoCollections), dutyInfoDT);
                            _mainView.Dispatcher.Invoke(new UpdateDelegate(UpdateListViewInfo), dutyInfoDT);
                        }
                    }


                }
                catch (System.Exception ex)
                {
                    MessageBoxHelper.ShowError(ex);
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.StackTrace);

                }
                Thread.Sleep(CONSTDATA.Driver_Tips_Interval);

            }
        }

        //显示提醒司机线程
        private void RemindDriverTherad()
        {
            RemindingDriverTherad = new Thread(new ThreadStart(RemindingDriver));
            RemindingDriverTherad.SetApartmentState(ApartmentState.STA);
            RemindingDriverTherad.IsBackground = true;
            RemindingDriverTherad.Start();
        }
        public bool CalcelShow(int id)
        {
            return _teamAccess.CancelShowRemind(id);
        }
        private void RemindingDriver()
        {
            while (true)
            {
                try
                {
                    DataTable driver = _teamAccess.GetDriverNeedRemind();
                    if (driver != null && driver.Rows.Count > 0)
                    {
                        _mainView.Dispatcher.Invoke(new UpdateDelegate(UpdateDriverNeedReminding), driver);
                    }

                }
                catch (System.Exception ex)
                {
                    MessageBoxHelper.ShowError(ex);
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.StackTrace);
                }
                Thread.Sleep(CONSTDATA.RemindingInterval);
            }
        }

        public void UpdateDriverNeedReminding(DataTable dt)
        {
            _mainView.dg_reminding.ItemsSource = dt.DefaultView;
            _mainView.dg_reminding.Tag = dt;
            bool canPlay = false;
            if (dt.Rows.Count > 0)
            {
                canPlay = true;
            }
            if (canPlay)
            {
                this._remindSoundPlayer.Play();
            }
        }

        private void UpdateDriverInfoCollections(DataTable DT)
        {
            int clsId = GetCurrentClassID();
            if (clsId == -1)
                return;

            string filter = "cls_id = " + clsId + " and actualAtten is null";

            DataRow[] DrInfos = DT.Select(filter);
            if (DrInfos == null)
                return;

            string currentTime = DateTime.Now.ToString("HH:mm:ss");
            bool canPlay = false;

            _mainDriverCollections.Clear();
            for (int i = 0; i < DrInfos.Length; i++)
            {
                CtlDutyInfo dutyInfo = new CtlDutyInfo();

                string user_name = DrInfos[i]["user_name"].ToString();
                dutyInfo.StaffName = DrInfos[i]["user_view_name"].ToString();
                dutyInfo.DutyTime = DrInfos[i]["planAtten"].ToString();
                if (string.IsNullOrEmpty(dutyInfo.DutyTime))
                    continue;
                dutyInfo.Phone = DrInfos[i]["user_pn"].ToString();
                dutyInfo.Checi = DrInfos[i]["reptrain"].ToString();

                string uriPath = GlobalVariables.LoadHeadImage(user_name);
                if (!string.IsNullOrEmpty(uriPath))
                    dutyInfo.ImageUri = uriPath;
                if (currentTime.CompareTo(dutyInfo.DutyTime) >= 0)
                {
                    // dutyInfo.Warn = true; 
                    canPlay = true;
                }

                _mainDriverCollections.Add(dutyInfo);
            }
            if (canPlay && IsVoiceOpen)
            {
                this._soundPlayer.Play();
            }
        }

        //private delegate void UpdateDelegate(DataTable dt);
        private void UpdateListViewInfo(DataTable dutyInfoDT)
        {
            _crossingRoadCollections.Clear();

            for (int i = 0; i < dutyInfoDT.Rows.Count; i++)
            {
                DutyInfoModel model = new DutyInfoModel();
                model.UserID = dutyInfoDT.Rows[i]["user_name"].ToString();
                model.UserName = dutyInfoDT.Rows[i]["user_view_name"].ToString();
                model.PlanAtten = dutyInfoDT.Rows[i]["planAtten"].ToString();
                model.PlanOut = dutyInfoDT.Rows[i]["planOut"].ToString();
                model.ActualAtten = dutyInfoDT.Rows[i]["actualAtten"].ToString();
                model.Place = dutyInfoDT.Rows[i]["attenPlace"].ToString();
                model.Reptrain = dutyInfoDT.Rows[i]["reptrain"].ToString();
                model.OutTime = dutyInfoDT.Rows[i]["outtime"].ToString();
                model._Class = dutyInfoDT.Rows[i]["cls_id"].ToString();
                model.PbyInfo = dutyInfoDT.Rows[i]["PbyInfo"].ToString();      
                model.DTQ = dutyInfoDT.Rows[i]["DTQ"].ToString();              
                _crossingRoadCollections.Add(model);
            }
        }

        private int GetCurrentClassID()
        {
            int result = -1;

            string timeNow = DateTime.Now.ToString("HH:mm:ss");
            if (timeNow.CompareTo(_bbShowTime) < 0) //早班
            {
                result = 0;
            }
            else if (timeNow.CompareTo(_bbShowTime) >= 0 && timeNow.CompareTo(_ybShowTime) < 0)//白班
            {
                result = 2;
            }
            else if (timeNow.CompareTo(_ybShowTime) >= 0) //夜班
            {
                result = 3;
            }

            return result;
        }

        /// <summary>
        /// 以班组的ID返回班组的名称 0：早班；1：休班；2：白班；3：夜班
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        private string GetClassNameByID(string ID)
        {
            string _class = "";
            switch (ID)
            {
                case "0":
                    _class = "早班";
                    break;
                case "1":
                    _class = "休班";
                    break;
                case "2":
                    _class = "白班";
                    break;
                case "3":
                    _class = "夜班";
                    break;
            }

            return _class;
        }

        private bool CheckCanAttend(string driClass)
        {
            bool canAttend = false;
            int currClass = GetCurrentClassID();
            switch (currClass)
            {
                case 0:
                    if (driClass == "0") { canAttend = true; }
                    break;
                case 2:
                    if (driClass == "0" || driClass == "2") { canAttend = true; }
                    break;
                case 3:
                    canAttend = true;
                    break;
            }
            return canAttend;
        }

        private bool CheckHasRefreshCrossRoad()
        {
            if (!_isCrossRoadAdd)
            {
                if (_teamAccess.CheckHasRefreshCrossRoad())
                    _isCrossRoadAdd = true;
            }
            return _isCrossRoadAdd;
        }

        private void onExecute(object papameter)
        {
            string command = (string)papameter;
            switch (command)
            {
                case "AddDriverView":
                    AddOutAndInDriver.GetInstance(new UpdateDelegate(UpdateListViewInfo)).Show();
                    break;
                case "SetChiefTimeView":
                    SetChiefDriversTime.GetInstance().Show();
                    break;
                case "ConfigurationView":
                    NewStatisticSetting.GetInstance().Show();
                    //StatisticSetting.GetInstance().Show();
                    break;
                case "Close":
                    this.Close();
                    break;
                case "InstructionFileView":
                    break;
                case "EditNoteView":
                    //NofityInputForm.GetInstance().Show();
                    new NofityView().Show();
                    break;
                case "VoiceCommand":
                    this.VoiceCommand_Method();
                    break;
                case "CrossingRoadView":
                    CrossingRoadView.GetInstance().Show();
                    break;
                case "DriverGroupManagementView":
                    DriverTeamManagerView.GetInstance().Show();
                    break;
                case "DriverAttendanceOrderAdjustView":
                    DriverAttendanceOrderAdjustView.GetInstance().Show();
                    break;
                case "NightShiftRommView":
                    BedRoomsView.GetInstances().Show();
                    break;
                case "SawtoothgraphView":
                    JCTFrm.GetInstance().Show();
                    break;
                case "ExcelTableview":
                    break;
                case "ClassTableView":
                    // AssignBB.GetInsatance().Show();
                    MonthlyPlan.GetInsatance().Show();
                    break;
                case "CSVFileView":
                    CSVFileView.GetInStance().Show();
                    break;
                case "ClassTableView2":
                    ExportScheduling.GetInsatance().Show();
                    break;
                case "TimeTableToDateView":
                    AssignTables.GetInstances().Show();
                    if (null == AssignTables.GetInstances().UpdateMainViewTimeTableAction)
                    {
                        AssignTables.GetInstances().UpdateMainViewTimeTableAction = this.LoadTimeTable;
                    }
                    break;
                case "StatisticsView":
                    StatisticsView.GetInstance().Show();
                    break;
            }

        }

        private void VoiceCommand_Method()
        {
            if (IsVoiceOpen)
            {
                _mainView.VoiceButtonChangeTemplate(!IsVoiceOpen);
            }
            else
            {
                _mainView.VoiceButtonChangeTemplate(!IsVoiceOpen);
            }

            IsVoiceOpen = !IsVoiceOpen;
        }

        private void AttendMethod()
        {

            string driverName = "";
            string driverClass = "";

            if (!AttenCheckAction(ref driverName, ref driverClass, true))
            {
                return;
            }

            //判断当前司机能否出勤
            if (!CheckCanAttend(driverClass))
            {
                MessageBoxHelper.ShowError(string.Format("尚未到司机 {0} 的出勤时间，或不属于当前出勤班组，请确认！", driverName));
                return;
            }
            string attendTime = "";

            if (_attendAccess.CheckHasAttend(_driverID, ref attendTime)) //如果已经出过勤的
            {
                if (!MessageBoxHelper.ConfirmYesNo(string.Format("工号:{0} 司机：{1}，在{2}，已出勤，是否更新其出勤时间？", _driverID, driverName, attendTime)))
                {
                    DriverID = string.Empty;
                    PasWrd = string.Empty;
                    return;
                }

            }

            //更新出勤时间
            if (_attendAccess.UpdateAttendTime(_driverID, ref attendTime))
            {
                //记录待出勤派班员的信息
                _attendAccess.UpdateAttenPBY(_driverID, CONSTDATA.UserModel.ID.ToString());
                MessageBoxHelper.ShowTips(string.Format("工号：{0} , {1} 司机出勤成功，当前出勤时间为:{2}", _driverID, driverName, attendTime));
                AddAttenInfo(new AttenInfoMedel() { UserID = _driverID, UserName = driverName, Action = "出勤", TimeInfo = attendTime });
                PasWrd = null;
                DriverID = null;
            }
            else
                MessageBoxHelper.ShowError("记录司机出勤时异常，请重试！");
        }

        private void OffWorkMethod()
        {
            string driverName = "";
            string driverClass = "";

            if (!AttenCheckAction(ref driverName, ref driverClass, false))
            {
                return;
            }

            string attendTime = "";
            if (!_attendAccess.CheckHasAttend(_driverID, ref attendTime)) //如果还没出过勤的，执行退勤操作
            {
                if (!MessageBoxHelper.ConfirmYesNo(string.Format("系统尚没记录司机{0}的出勤时间，是否现在记录其退勤时间？", driverName))) ;
                return;
            }
            //更新退勤时间
            string offTime = "";
            if (_attendAccess.UpdateOffWorkTime(_driverID, ref offTime))
            {
                _attendAccess.UpdateDTQ(_driverID, CONSTDATA.UserModel.ID.ToString());
                MessageBoxHelper.ShowTips(string.Format("工号：{0} , {1} 司机退勤成功，当前退勤时间为:{2}", _driverID, driverName, offTime));

                AddAttenInfo(new AttenInfoMedel() { UserID = _driverID, UserName = driverName, Action = "退勤", TimeInfo = offTime });
                PasWrd = null;
                DriverID = null;

            }
            else
                MessageBoxHelper.ShowError("记录司机出勤时异常，请重试！");

        }

        private bool AttenCheckAction(ref string driverName, ref string driverClass, bool chuQin)
        {
            bool result = false;



            if (!ValidateInput())
            {
                MessageBoxHelper.ShowError("请正确输入工号及密码后重试！");
                return result;
            }
            string sql="select name from [CanReplaceAttendancePosition]";
            DataTable ReplaceAttendceTable =new SqlDataLayer().SelectDt(sql);
            if (ReplaceAttendceTable.Select("name='"+CONSTDATA.UserModel.DepartName +"'").Length<=0)
            {
                  MessageBoxHelper.ShowError("派班员账号登录后可使用协助出退勤功能，请确认！");
                return result;
            }
            //if (CONSTDATA.UserModel.DepartName != "派班员" && CONSTDATA.UserModel.DepartName != "系统管理员" && (CONSTDATA.UserModel.DepartName!="司机长" ||CONSTDATA.UserModel.DepartName!="电客车司机长"))
            //{
            //    MessageBoxHelper.ShowError("派班员账号登录后可使用协助出退勤功能，请确认！");
            //    return result;
            //}

            if (!_attendAccess.CheckPasWrdValidation(CONSTDATA.UserModel.UserID, _pasWrd))
            {
                MessageBoxHelper.ShowError("密码错误，无法执行出勤操作，请确认！");
                return result;
            }

            DataTable dtDutyDriver = _attendAccess.GetDutyDriver(_driverID, DateTime.Now.ToString("yyyy-MM-dd"), UserModel.Line);

            if (dtDutyDriver != null && dtDutyDriver.Rows.Count > 0)
            {
                //本职出勤记录
                DataRow dutyRow = null;
                //代班出勤记录
                DataRow replaceRow = null;

                foreach (DataRow row in dtDutyDriver.Rows)
                {
                    if (row["dutyId"].ToString() == _driverID)
                        dutyRow = row;
                    else if (row["replaceId"].ToString() == _driverID)
                    {
                        if (replaceRow != null)
                        {
                            if ((replaceRow["dgrp_attendtime"] == DBNull.Value && row["dgrp_attendtime"] == DBNull.Value) ||
                                (replaceRow["dgrp_attendtime"] != DBNull.Value && row["dgrp_attendtime"] != DBNull.Value))
                            {
                                int timeDT1 = GlobalVariables.FormatTimeToInt(replaceRow["planTime"].ToString()) - GlobalVariables.FormatTimeToInt(DateTime.Now);
                                int timeDT2 = GlobalVariables.FormatTimeToInt(row["planTime"].ToString()) - GlobalVariables.FormatTimeToInt(DateTime.Now);
                                if (Math.Abs(timeDT1) > Math.Abs(timeDT2))
                                {
                                    replaceRow = row;
                                }
                            }
                            else if (row["dgrp_attendtime"] == DBNull.Value)
                            {
                                replaceRow = row;
                            }

                        }
                        else
                            replaceRow = row;
                    }
                }
                driverName = dutyRow["dutyname1"].ToString();
                if (dutyRow != null && replaceRow != null)
                {
                    //本职出勤与代班出勤均有记录
                    string columnName = null;
                    if (chuQin)
                        columnName = "dgrp_attendtime";
                    else
                        columnName = "dgrp_outtime";


                    if (dutyRow[columnName] == DBNull.Value && replaceRow[columnName] != DBNull.Value)
                    {
                        //当代班已经出勤而本职未出勤
                        //而且如果本职已经有人替代，则司机代班出勤
                        //否则本职出勤
                        if (dutyRow["replaceDriver"] != DBNull.Value)
                        {
                            _driverID = replaceRow["dutyId"].ToString();
                           
                            driverName = replaceRow["replacename1"].ToString() + "(替" + replaceRow["dutyname1"].ToString() + ")";
                            
                        }
                    }
                    else if (dutyRow[columnName] != DBNull.Value && replaceRow[columnName] == DBNull.Value)
                    {
                        //代班未出勤而本职已出勤，则司机代班出勤
                        _driverID = replaceRow["dutyId"].ToString();
                        driverName = replaceRow["replacename1"].ToString() + "(替" + replaceRow["dutyname1"].ToString() + ")";
                        
                    }
                    else if (dutyRow[columnName] == DBNull.Value && replaceRow[columnName] == DBNull.Value)
                    {
                        //代班本职均未出勤，通过判断出勤属于代班出勤还是本职出勤

                        if (dutyRow["replaceDriver"] == DBNull.Value)
                        {
                            //当本职出勤没有人代班时
                            int dutyTimeDT = GlobalVariables.FormatTimeToInt(dutyRow["planTime"].ToString()) - GlobalVariables.FormatTimeToInt(DateTime.Now);
                            int replaceTimeDT = GlobalVariables.FormatTimeToInt(replaceRow["planTime"].ToString()) - GlobalVariables.FormatTimeToInt(DateTime.Now);
                            if (Math.Abs(dutyTimeDT) > Math.Abs(replaceTimeDT))
                            {
                                _driverID = replaceRow["dutyId"].ToString();
                                driverName = replaceRow["replacename1"].ToString() + "(替" + replaceRow["dutyname1"].ToString() + ")";
                            }
                        }
                        else
                        {
                            //当本职出勤已经有人代班时，按照正常代班出勤
                            _driverID = replaceRow["dutyId"].ToString();
                            driverName = replaceRow["replacename1"].ToString() + "(替" + replaceRow["dutyname1"].ToString() + ")";
                        }

                    }
                    else
                    {
                        //均已出勤,按照原来流程本职出勤，判断出勤现在跟哪条出勤记录时间相近
                        if (dutyRow["replaceDriver"] == DBNull.Value)
                        {
                            //当本职出勤没有人代班时
                            int dutyTimeDT = GlobalVariables.FormatTimeToInt(dutyRow["planTime"].ToString()) - GlobalVariables.FormatTimeToInt(DateTime.Now);
                            int replaceTimeDT = GlobalVariables.FormatTimeToInt(replaceRow["planTime"].ToString()) - GlobalVariables.FormatTimeToInt(DateTime.Now);
                            if (Math.Abs(dutyTimeDT) > Math.Abs(replaceTimeDT))
                            {
                                _driverID = replaceRow["dutyId"].ToString();
                                driverName = replaceRow["replacename1"].ToString() + "(替" + replaceRow["dutyname1"].ToString() + ")";
                            }
                        }
                        else
                        {
                            //当本职出勤已经有人代班时，按照正常代班出勤
                            _driverID = replaceRow["dutyId"].ToString();
                            driverName = replaceRow["replacename1"].ToString() + "(替" + replaceRow["dutyname1"].ToString() + ")";
                        }
                    }
                }
                else if (replaceRow != null)
                {
                    //当只有代班出勤记录时，则出勤代班记录，其他条件不需要处理
                    _driverID = replaceRow["dutyId"].ToString();
                    driverName = replaceRow["replacename1"].ToString() + "(替" + replaceRow["dutyname1"].ToString() + ")";
                }
                else if (dutyRow["replaceDriver"] != DBNull.Value)
                {
                    MessageBoxHelper.ShowError("司机今天没有出勤任务！");
                    return result;
                }
            }
            else
            {
                MessageBoxHelper.ShowTips("无司机出勤信息或找不到用户信息");
                return result;
            }

            //if (IsReplace)
            //{
            //    _driverID = _attendAccess.GetReplaceDriver(_driverID);
            //}
            if (!_attendAccess.CheckUserIsDriver(_driverID))  //判断是否为司机
            {
                if (string.IsNullOrEmpty(driverName))
                    MessageBoxHelper.ShowError("无此用户信息，请确认！");
                else
                    MessageBoxHelper.ShowError(string.Format("工号:{0},姓名:{1},不属电客车司机，无法执行出勤操作，请确认！", _driverID, driverName));
                return result;
            }

            //属于哪个班组，早、白、夜
            driverClass = _attendAccess.GetDriverClass(_driverID);
            if (string.IsNullOrEmpty(driverClass) || GetClassNameByID(driverClass) == "休班") //"休班"
            {
                MessageBoxHelper.ShowError(string.Format("司机{0} 今天没有出勤任务！", driverName));
                return result;
            }

            result = true;

            return result;
        }

        private void AddAttenInfo(AttenInfoMedel item)
        {
            this.AttendInfoList.Add(item);
            //OnPropertyChanged("AttendInfoList");
        }

        private bool ValidateInput()
        {
            return !string.IsNullOrEmpty(_driverID) && !string.IsNullOrEmpty(_pasWrd);
        }

        private void SelDriverByListView()
        {
            string driverID = _mainView.cbbdriver.SelectedValue.ToString();
            var model = _crossingRoadCollections.First(a => a.UserID == driverID);
            int index = _crossingRoadCollections.IndexOf(model);
            this._mainView.listView.SelectedIndex = index;
            this._mainView.listView.ScrollIntoView(model);
        }

        public string GetVersion()
        {
            return _attendAccess.GetVersion();
        }

        public void Dispose()
        {
            if (UpdateDutyInfoThread != null)
            {
                try
                {
                    UpdateDutyInfoThread.Abort();
                }
                catch (System.Exception ex)
                {

                }
                finally { UpdateDutyInfoThread = null; }
            }
            if (RemindingDriverTherad != null)
            {
                try
                {
                    RemindingDriverTherad.Abort();
                }
                catch (System.Exception e)
                {

                }
                finally
                {
                    RemindingDriverTherad = null;
                }
            }
            if (_soundPlayer != null)
                _soundPlayer.Dispose();

            if (_remindSoundPlayer != null)
            {
                _remindSoundPlayer.Dispose();
            }
        }
    }
}
